'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from twisted.internet.protocol import ServerFactory
from dopplershift.collector.shell.protocol import CollectorShellProtocol
from dopplershift.core.containers.mediator import getMediator
from twisted.internet import reactor
import os

class CollectorShellFactory(ServerFactory):
    protocol = CollectorShellProtocol
    def __init__(self):
        self._mediator = getMediator()
    def command(self, obj, callback):
        if hasattr(self, 'do_%s'%obj['command']):
            cmd = getattr(self, 'do_%s'%obj['command'])
            cmd(obj, callback)
            return
        callback({"error": "unknown command"})
            
    def do_reload(self, obj, callback):
        '''
        reload collector templates
        '''
        res = self._mediator.get('CollectorTemplates').reload()
        callback({"reload": res})
    def do_update(self, obj, callback):
        '''
        update server configuration (without socket bindings)
        '''
        callback({"update": True})
    def do_flush(self, obj, callback):
        '''
        flush all cached data in local memory
        '''
        callback({"flush": True})
    def flushkey(self, obj, callback):
        '''
        flush one callid from local memory cache
        '''
        callback({"flushkey":{ "key": obj['key'], "result": True}})
        
def collector_shell_builder(port_number):
    mediator = getMediator()
    cfg = mediator.get("CollectorConfig")
    setting = cfg.get_setting("unix_socket")
   
    if setting != None and 'path' in setting:
        csf = CollectorShellFactory()
        mediator.register("CollectorShell", csf)
        reactor.listenUNIX(os.path.join(setting['path'], "dopplershift_%s"%port_number), csf)
